import os, sys
import mimetypes
import email.Charset
email.Charset.add_charset('utf-8', email.Charset.SHORTEST, None, None)
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email import Encoders
import smtplib
import cStringIO
from datetime import datetime
import time


class Mailer(object):
    """base mailer class"""
    def __init__(self, mailFrom=None, mailTo=None, subject=None, body=None, type=None):
        if not isinstance(mailTo, list):
            self.mailTo = mailTo
            self.mailList = [mailTo]
        else:
            self.mailTo = ', '.join(mailTo)
            self.mailList = mailTo
        self.mailFrom = mailFrom
        self.subject = subject
        self.body = body
        self.type = type
        if self.type is None:
            self.type = "plain"
        if self.mailTo is None:
            raise Exception("Must have at least a mail to address")
        if self.mailFrom is None:
            self.mailFrom = 'document_report_mailer@thig.com'
        if self.type == "plain":
            self.message = MIMEText(str(body), 'plain')
        elif self.type == "mime":
            self.message = MIMEMultipart() 
            self.message["Mime-version"] = "1.0"
            self.message["Content-type"] = "Multipart/mixed"
            self.message.preamble = "Mime Message\n"
            self.contentType = 'application/octet-stream'
            self.cte = 'base64' #Content-transfer-encoding
            self.message.epilogue = "\n"
            
        self.message["To"] = str(self.mailTo)
        self.message["From"] = str(self.mailFrom)
        self.message["Subject"] = str(self.subject)
        self.message["Date"] = str(datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z'))

    def mail(self):
        smtp = smtplib.SMTP('localhost')
        smtp.sendmail(self.mailFrom, self.mailList, self.message.as_string())



class ReportMailer(Mailer):
    """class to generate mail attachments and send mail"""

    def __init__(self, mailFrom=None, mailTo=None, subject=None, body=None, type="mime"):
        if subject is None:
            subject = "Document Report Mail"
        if mailTo is None:
            mailTo = 'doc_report_mail@thig.com'
        if body is None:
            body = "Document Reports for %s" % datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
        super(ReportMailer, self).__init__(mailFrom, mailTo, subject, body, type)
        self.contentType = 'text/plain'
        self.cte = 'quoted-printable'


    def mailReports(self, contents):
        for (attachment, type) in contents:
            subMsg = MIMEBase('text', 'plain')
            subMsg.set_payload(attachment)
            Encoders.encode_quopri(subMsg)
            subMsg.add_header("Content-Disposition", 'attachment; filename=%s.csv'% type)
            self.message.attach(subMsg)
        self.mail()
